﻿using System.Collections.Specialized;
using System.Windows;
using System.Windows.Input;
using DesktopToyWpf.ViewModels;

namespace DesktopToyWpf.Views;

/// <summary>
/// Interaction logic for MoodControl.xaml
/// </summary>
public partial class MoodControl
{
    public MoodControl()
    {
        InitializeComponent();
    }

    private MainViewModel? ViewMode => DataContext as MainViewModel;

    private const double TOO_CLOSE = 0.1d; 
    
    private void MoodSlider_OnValueChanged(object sender, RoutedEventArgs<int> e)
    {
        UpdateCurrentMood(e.Data);
    }

    private void MoodControl_OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var vm = ViewMode;
        if(vm == null) return;

        if (e.OldValue is MainViewModel oldValue)
        {
            oldValue.MoodPoints.CollectionChanged -= MoodPoints_OnCollectionChanged;
            MoodProgressBar.Points = null;
        }
        
        if (e.NewValue is MainViewModel newValue)
        {
            newValue.MoodPoints.CollectionChanged += MoodPoints_OnCollectionChanged;
            MoodProgressBar.Points = newValue.MoodPoints;
        }
        
        MoodProgressBar.InvalidateVisual();
    }

    private void MoodPoints_OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
    {
        MoodProgressBar.InvalidateVisual();
    }

    private void UIElement_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        UpdateCurrentMood(MoodSlider.Value);
    }

    private void UpdateCurrentMood(int mood)
    {
        var vm = ViewMode;
        if(vm == null) return;

        var point = new Point(vm.Now.Hour + vm.Now.Minute / 60d, mood);

        if (vm.MoodPoints.Count == 0)
        {
            vm.MoodPoints.Add(point);
        }
        else
        {
            var last = vm.MoodPoints.Last();
            if (Math.Abs(last.X - point.X) <= TOO_CLOSE) // 相同X
            {
                vm.MoodPoints[^1] = point;
            }
            else
            {
                vm.MoodPoints.Add(point);
            }
        }

        MoodProgressBar.Points = vm.MoodPoints;
        MoodProgressBar.InvalidateVisual();
    }

    private void MoodSlider_OnMouseUp(object sender, MouseButtonEventArgs e)
    {
        Global.SaveStorage();
    }
}